import 'package:commons/commons.dart' hide Response;
import 'package:dio/dio.dart';

class DioLogger extends Interceptor {
  @override
  void onResponse(
    Response<dynamic> response,
    ResponseInterceptorHandler handler,
  ) {
    ILog.l([
      response.requestOptions.uri,
      response.requestOptions.method,
      '------headers------',
      response.requestOptions.headers,
      '------parameters------',
      getParam(response),
      '------response------',
      response.data,
    ]);
    super.onResponse(response, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    ILog.l([
      '-----Error-----',
      err.requestOptions.uri,
      err.requestOptions.method,
      '------headers------',
      err.requestOptions.headers,
      '------parameters------',
      getParam(err.response!),
      err.response?.statusCode,
      '------response------',
      err.response?.data,
    ]);
    super.onError(err, handler);
  }
}

extension DioLoggerExtension on DioLogger {
  dynamic getParam(Response<dynamic> response) {
    if (response.requestOptions.queryParameters.isNotEmpty) {
      return response.requestOptions.queryParameters;
    }

    return response.requestOptions.data;
  }
}
